package edu.whu.irlab.util.time;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 通过标准时间和偏移量来确定时间
 * Created by 声伟 on 2014/4/26 0026.
 */
public class ShiftStandardizer implements DateStandardizer {
    public static final String regex = "(\\d+)(.+?)前|(\\d+)(.+?)ago";
    private int[] group = new int[2];   //分别指明偏移数，和偏移字段
    private int shift = 0;
    private String label = "";
    private Date time;    //规范时间：2014-01-11 23:23:03
    private String[] hourLabel = {"小时", "hours", "hour", "时"};
    private List<String> hourLabelList = Arrays.asList(hourLabel);
    private String[] dayLabel = {"天", "day", "days"};
    private List<String> dayLabelList = Arrays.asList(dayLabel);
    private String[] minuteLabel = {"分钟", "minute", "minutes"};
    private List<String> minuteLabelList = Arrays.asList(minuteLabel);
    private String[] secondLabel = {"秒", "second", "seconds"};
    private List<String> secondLabelList = Arrays.asList(secondLabel);

    public ShiftStandardizer(int[] groupNumArr, Date time) {
        this.group = groupNumArr;
        this.time = time;
    }

    @Override
    public Timestamp get(String date) {
        if (date == null || date.trim().equals("")) {
            return null;
        }
        Pattern pt = Pattern.compile(regex);
        Matcher mt = pt.matcher(date);
        if (mt.find()) {
            shift = Integer.parseInt(mt.group(group[0]));
            if (shift <= 0) {
                return null;
            }
            label = mt.group(group[1]);
            if (label.equals("")) {
                return null;
            }
            return standard(shift, label, time);
        }
        return null;
    }

    private Timestamp standard(int shift, String label, Date time) {
        Calendar standardTime = Calendar.getInstance();
        standardTime.setTime(time);
        if (hourLabelList.contains(label)) {
            standardTime.add(Calendar.HOUR_OF_DAY, -shift);
            standardTime.set(Calendar.MINUTE, 0);
            standardTime.set(Calendar.SECOND, 0);
        } else if (dayLabelList.contains(label)) {
            standardTime.add(Calendar.DAY_OF_MONTH, -shift);
            standardTime.set(Calendar.HOUR_OF_DAY, 0);
            standardTime.set(Calendar.MINUTE, 0);
            standardTime.set(Calendar.SECOND, 0);
        } else if (minuteLabelList.contains(label)) {
            standardTime.add(Calendar.MINUTE, -shift);
            standardTime.set(Calendar.SECOND, 0);
        } else if (secondLabelList.contains(label)) {
            standardTime.add(Calendar.SECOND, -shift);
        } else {
            return null;
        }
        return new Timestamp(standardTime.getTime().getTime());
    }
}
